package com.ext.aic.handler;

import android.os.Handler;
import android.text.Editable;

import com.ext.aic.components.ObservableRTEditText;

public class TypeWriterHandler {

    private Handler handler = new Handler();
    private Runnable typeRunnable;

    protected void onComplete() {

    }

    public void startAutoType(ObservableRTEditText editRte, String text) {
        final int delayMillis = 10; // 每个字符的延迟时间（毫秒）
        // 确保在UI线程操作
        handler.post(new Runnable() {
            int index = 0;

            @Override
            public void run() {
                if (index < text.length()) {
                    // 获取当前光标位置
                    int position = editRte.getSelectionStart();
                    // 插入字符
                    Editable editable = editRte.getText();
                    editable.insert(position, String.valueOf(text.charAt(index)));
                    // 移动光标到新位置
                    editRte.setSelection(position + 1);
                    // 滚动到光标位置
                    editRte.bringPointIntoView(position + 1);
                    editRte.setCursorVisible(true);
                    editRte.requestFocus();
                    index++;
                    // 继续下一个字符
                    handler.postDelayed(this, delayMillis);
                } else {
                    onComplete();
                }
            }
        });
    }

    public void destroy() {
        if (handler != null && typeRunnable != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
